package cn.daniellee.plugin.el.runnable;

import cn.daniellee.plugin.el.EnterLimiter;
import cn.daniellee.plugin.el.component.ActionSender;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;

import java.util.List;

public class LimiterRunnable extends BukkitRunnable {

	@Override
	public void run() {
		String fallbackServer = EnterLimiter.getInstance().getConfig().getString("setting.fallback-server", "Lobby");
		List<Player> players = (List<Player>) Bukkit.getOnlinePlayers();
		for (Player player : players) {
			if (player.hasPermission("enterlimiter.bypass")) continue;
			Integer available = EnterLimiter.availableSecond.get(player.getName());
			if (available == null || available == 0) {
				player.sendMessage((EnterLimiter.getInstance().getPrefix() + EnterLimiter.getInstance().getConfig().getString("message.time-out", "&eYour time has run out and will be sent out of this server.")).replace("&", "§"));
				// 更新Map
				EnterLimiter.availableSecond.remove(player.getName());
				// 仅在用完的时候保存到文件
				EnterLimiter.getInstance().getPlayerData().set(player.getName() + ".available", null);
				EnterLimiter.getInstance().savePlayerData();
				// 发送插件信息
				ByteArrayDataOutput out = ByteStreams.newDataOutput();
				out.writeUTF("Connect");
				out.writeUTF(fallbackServer);
				player.sendPluginMessage(EnterLimiter.getInstance(), "BungeeCord", out.toByteArray());
			} else {
				ActionSender.send(player, EnterLimiter.getInstance().getConfig().getString("message.action-bar.remaining", "&eRemaining: &b{hour}h {minute}m {second}s").replace("{hour}", Integer.toString(available / 3600)).replace("{minute}", Integer.toString(available % 3600 / 60)).replace("{second}", Integer.toString(available % 60)).replace("&", "§"));
				EnterLimiter.availableSecond.put(player.getName(), available - 1);
			}
		}
	}

}
